/**
 * 医院管理页面
 * 整合医院建筑管理、科室绑定、设备管理、3D地图查看、AI助手等功能
 */

'use client'

import React, { useState, useRef, useEffect } from 'react'
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"
import { Button } from "@/components/ui/button"
import { Badge } from "@/components/ui/badge"
// import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"
import { toast } from 'sonner'
import { Building2, Database, Bot, Eye, EyeOff, Stethoscope } from 'lucide-react'

// 组件导入
import { DynamicHospitalMapViewer } from '@/components/Dynamic3DViewer'
import { HospitalAIAssistant } from '@/components/hospital/HospitalAIAssistant'
import { HospitalManagementPanel } from '@/components/hospital/HospitalManagementPanel'
import { initDemoData } from '@/lib/demo-data'
import { testDatabase } from '@/lib/test-db'

interface HospitalInfo {
  id: string
  name: string
  address: string
  center: [number, number]
}

interface BuildingInfo {
  id: string
  hospitalId: string
  name: string
  description: string
  center: [number, number]
  modelPath: string
  floors: string[]
}

export default function HospitalManagementPage() {
  const [selectedHospital, setSelectedHospital] = useState<HospitalInfo | null>(null)
  const [selectedBuilding, setSelectedBuilding] = useState<BuildingInfo | null>(null)
  const [showDataPanel, setShowDataPanel] = useState(true)
  const [showAIAssistant, setShowAIAssistant] = useState(true)
  const [isInitialized, setIsInitialized] = useState(false)
  const mapViewerRef = useRef<any>(null)

  // 初始化演示数据
  useEffect(() => {
    const initializeData = async () => {
      try {
        console.log('正在初始化医院演示数据...')
        await initDemoData()
        setIsInitialized(true)
        
        // 延迟一点时间确保数据完全加载后再通知面板刷新
        setTimeout(() => {
          toast.success('医院演示数据已加载')
          // 强制刷新页面数据显示
          window.dispatchEvent(new Event('hospital-data-updated'))
        }, 500)
      } catch (error) {
        console.error('初始化演示数据失败:', error)
        toast.error('初始化演示数据失败，请刷新页面重试')
      }
    }

    initializeData()
  }, [])

  // 处理医院选择
  const handleHospitalSelect = (hospital: HospitalInfo) => {
    setSelectedHospital(hospital)
    setSelectedBuilding(null)
    if (hospital) {
      toast.success(`已切换到医院: ${hospital.name}`)
      // 地图飞行到医院中心
      mapViewerRef.current?.flyTo(hospital.center, 16)
    }
  }

  // 处理建筑选择
  const handleBuildingSelect = (building: BuildingInfo) => {
    setSelectedBuilding(building)
    if (building) {
      toast.success(`已选择建筑: ${building.name}`)
      // 地图飞行到建筑中心
      mapViewerRef.current?.flyTo(building.center, 18)
    }
  }

  // 处理模型刷新
  const handleRefreshModel = () => {
    toast.success('正在刷新3D模型...')
    mapViewerRef.current?.refreshModel()
    mapViewerRef.current?.refreshDepartments()
    mapViewerRef.current?.refreshEquipment()
  }

  // 处理数据变更
  const handleDataChange = () => {
    // 刷新地图上的标记
    mapViewerRef.current?.refreshDepartments()
    mapViewerRef.current?.refreshEquipment()
  }

  // AI助手导航回调
  const handleAINavigation = (location: { lng: number; lat: number }) => {
    mapViewerRef.current?.flyTo([location.lng, location.lat], 18)
    toast.success('正在为您导航...')
  }

  // AI助手科室选择回调
  const handleAIDepartmentSelect = (department: { name: string; position?: [number, number] }) => {
    toast.success(`已选择科室: ${department.name}`)
    if (department.position) {
      mapViewerRef.current?.flyTo(department.position, 18)
    }
  }

  // AI助手预约回调
  const handleAIBookAppointment = (department: { name: string }) => {
    toast.success(`正在为您预约${department.name}...`)
    // 这里可以跳转到预约页面
  }

  return (
    <div className="h-screen bg-gray-50 flex flex-col overflow-hidden">
      {/* 页面头部 */}
      <div className="bg-white border-b px-6 py-4 flex-shrink-0">
        <div className="flex items-center justify-between">
          <div>
            <h1 className="text-2xl font-bold text-gray-900 flex items-center gap-2">
              <Building2 className="w-6 h-6 text-blue-600" />
              医院数字孪生管理平台
            </h1>
            <p className="text-gray-600 mt-1">集成3D地图、科室绑定、设备管理、AI医疗助手的智慧医院系统</p>
          </div>

          <div className="flex items-center gap-2">
            {selectedHospital && (
              <Badge variant="secondary" className="px-3 py-1">
                当前医院: {selectedHospital.name}
              </Badge>
            )}
            {selectedBuilding && (
              <Badge variant="outline" className="px-3 py-1">
                建筑: {selectedBuilding.name}
              </Badge>
            )}

            <Button
              variant="outline"
              size="sm"
              onClick={() => setShowDataPanel(!showDataPanel)}
              className="gap-1"
            >
              <Database className="w-4 h-4" />
              {showDataPanel ? <EyeOff className="w-4 h-4" /> : <Eye className="w-4 h-4" />}
              数据面板
            </Button>

            <Button
              variant="outline"
              size="sm"
              onClick={() => setShowAIAssistant(!showAIAssistant)}
              className="gap-1"
            >
              <Bot className="w-4 h-4" />
              {showAIAssistant ? <EyeOff className="w-4 h-4" /> : <Eye className="w-4 h-4" />}
              AI助手
            </Button>

            <Button
              variant="outline"
              size="sm"
              onClick={async () => {
                try {
                  await initDemoData()
                  toast.success('数据重新初始化完成')
                  window.location.reload()
                } catch (error) {
                  toast.error('数据初始化失败')
                }
              }}
              className="gap-1"
            >
              🔄 重新初始化
            </Button>

            <Button
              variant="outline"
              size="sm"
              onClick={async () => {
                const result = await testDatabase()
                if (result) {
                  toast.success('数据库测试完成，请查看控制台')
                } else {
                  toast.error('数据库测试失败')
                }
              }}
              className="gap-1"
            >
              🔍 测试数据库
            </Button>
          </div>
        </div>
      </div>

      {/* 主要内容区域 */}
      <div className="flex-1 flex overflow-hidden">
        {/* 左侧数据管理面板 */}
        {showDataPanel && (
          <div className="w-96 bg-white border-r flex-shrink-0 overflow-hidden">
            <div className="h-full overflow-y-auto">
              <HospitalManagementPanel
                className="p-4"
                onHospitalSelect={handleHospitalSelect}
                onBuildingSelect={handleBuildingSelect}
                onRefreshModel={handleRefreshModel}
              />
            </div>
          </div>
        )}

        {/* 中间3D地图区域 */}
        <div className="flex-1 relative overflow-hidden">
          {selectedHospital && selectedBuilding ? (
            <>
              {/* 地图显示模式控制 */}
              <div className="absolute top-4 left-4 z-30 bg-white/95 backdrop-blur-sm rounded-lg border shadow-sm">
                <div className="flex flex-col p-3 space-y-2">
                  <div className="text-xs font-medium text-gray-700">显示模式</div>
                  <div className="flex flex-wrap gap-2">
                    <Button size="sm" variant="default" className="text-xs h-7 px-3">
                      🏥 概览
                    </Button>
                    <Button size="sm" variant="outline" className="text-xs h-7 px-3">
                      🏥 科室
                    </Button>
                    <Button size="sm" variant="outline" className="text-xs h-7 px-3">
                      🔬 设备
                    </Button>
                    <Button size="sm" variant="outline" className="text-xs h-7 px-3">
                      ⚠️ 告警
                    </Button>
                  </div>
                </div>
              </div>

              <DynamicHospitalMapViewer
                ref={mapViewerRef}
                hospital={selectedHospital}
                building={selectedBuilding}
                className="w-full h-full"
                onDataChange={handleDataChange}
              />
            </>
          ) : (
            <div className="flex items-center justify-center h-full bg-gray-100">
              <Card className="w-96">
                <CardHeader className="text-center">
                  <div className="w-16 h-16 bg-blue-100 rounded-full flex items-center justify-center mx-auto mb-4">
                    <Building2 className="w-8 h-8 text-blue-600" />
                  </div>
                  <CardTitle>欢迎使用医院数字孪生系统</CardTitle>
                </CardHeader>
                <CardContent className="text-center space-y-4">
                  <div className="bg-yellow-50 border border-yellow-200 p-3 rounded-lg">
                    <div className="text-sm text-yellow-800">
                      系统状态: {isInitialized ? '✅ 已初始化' : '⏳ 初始化中...'}
                    </div>
                    <div className="text-xs text-yellow-700 mt-1">
                      {!selectedHospital
                        ? '请在左侧数据面板中选择医院'
                        : '请选择一个医院建筑查看3D地图'
                      }
                    </div>
                  </div>

                  <div className="grid grid-cols-2 gap-3 text-sm">
                    <div className="p-3 bg-blue-50 rounded-lg">
                      <div className="font-medium text-blue-900">🗺️ 3D地图</div>
                      <div className="text-blue-700 mt-1">高德地图+Three.js</div>
                    </div>
                    <div className="p-3 bg-green-50 rounded-lg">
                      <div className="font-medium text-green-900">🏥 科室绑定</div>
                      <div className="text-green-700 mt-1">科室+设备管理</div>
                    </div>
                    <div className="p-3 bg-purple-50 rounded-lg">
                      <div className="font-medium text-purple-900">🤖 AI助手</div>
                      <div className="text-purple-700 mt-1">智能导航+医疗咨询</div>
                    </div>
                    <div className="p-3 bg-orange-50 rounded-lg">
                      <div className="font-medium text-orange-900">💾 本地存储</div>
                      <div className="text-orange-700 mt-1">IndexedDB数据库</div>
                    </div>
                  </div>

                  <div className="pt-4 border-t">
                    <p className="text-xs text-gray-500">
                      💡 点击建筑绑定科室，点击地面绑定医疗设备
                    </p>
                    {!isInitialized && (
                      <p className="text-xs text-orange-500 mt-2">
                        如果长时间未初始化，请点击"重新初始化"按钮
                      </p>
                    )}
                  </div>
                </CardContent>
              </Card>
            </div>
          )}

          {/* 地图控制器 */}
          {selectedHospital && selectedBuilding && (
            <div className="absolute top-4 left-4 space-y-2">
              <Card className="p-3">
                <div className="text-sm font-medium text-gray-700 mb-2">
                  🎮 操作指南
                </div>
                <div className="text-xs text-gray-600 space-y-1">
                  <div>• 点击建筑物：绑定科室信息</div>
                  <div>• 点击地面：绑定医疗设备</div>
                  <div>• 拖拽：移动地图视角</div>
                  <div>• 滚轮：缩放地图</div>
                </div>
              </Card>

              <Card className="p-3">
                <div className="text-sm font-medium text-gray-700 mb-2">
                  🏥 当前信息
                </div>
                <div className="text-xs text-gray-600 space-y-1">
                  <div>🏛️ {selectedHospital.name}</div>
                  <div>🏢 {selectedBuilding.name}</div>
                  <div>🌐 {selectedBuilding.center[0].toFixed(4)}, {selectedBuilding.center[1].toFixed(4)}</div>
                  <div>🏗️ {selectedBuilding.modelPath}</div>
                </div>
              </Card>
            </div>
          )}
        </div>

        {/* 右侧管理面板 */}
        <div className="w-80 bg-white border-l flex-shrink-0 overflow-hidden">
          <div className="h-full flex flex-col">
            {/* 面板头部 */}
            <div className="p-4 border-b">
              <div className="flex items-center justify-between">
                <h3 className="font-medium text-gray-900">管理面板</h3>
                <Badge variant="secondary" className="text-xs">
                  {selectedHospital ? '已连接' : '未选择'}
                </Badge>
              </div>
            </div>

            {/* 面板内容 */}
            <div className="flex-1 overflow-y-auto p-4 space-y-4">
              {/* 当前选择信息 */}
              {selectedHospital && (
                <Card>
                  <CardHeader className="pb-2">
                    <CardTitle className="text-sm">当前医院</CardTitle>
                  </CardHeader>
                  <CardContent className="text-xs space-y-2">
                    <div className="flex justify-between">
                      <span>名称:</span>
                      <span className="font-medium">{selectedHospital.name}</span>
                    </div>
                    <div className="flex justify-between">
                      <span>地址:</span>
                      <span className="font-medium text-gray-600">{selectedHospital.address}</span>
                    </div>
                    <div className="flex justify-between">
                      <span>坐标:</span>
                      <span className="font-medium">{selectedHospital.center[0].toFixed(4)}, {selectedHospital.center[1].toFixed(4)}</span>
                    </div>
                    {selectedBuilding && (
                      <>
                        <div className="border-t pt-2 mt-2">
                          <div className="flex justify-between">
                            <span>建筑:</span>
                            <span className="font-medium">{selectedBuilding.name}</span>
                          </div>
                          <div className="flex justify-between">
                            <span>楼层:</span>
                            <span className="font-medium">{selectedBuilding.floors.join(', ')}</span>
                          </div>
                        </div>
                      </>
                    )}
                  </CardContent>
                </Card>
              )}

              {/* 突发事件管理 */}
              <Card>
                <CardHeader className="pb-2">
                  <CardTitle className="text-sm flex items-center justify-between">
                    突发事件管理
                    <Button size="sm" variant="outline" className="text-xs h-6">
                      开始演示
                    </Button>
                  </CardTitle>
                </CardHeader>
                <CardContent>
                  <div className="space-y-2">
                    <div className="flex gap-2">
                      <Button size="sm" variant="outline" className="flex-1 text-xs">
                        🔥 火灾
                      </Button>
                      <Button size="sm" variant="outline" className="flex-1 text-xs">
                        🚑 医疗
                      </Button>
                    </div>
                    <div className="flex gap-2">
                      <Button size="sm" variant="outline" className="flex-1 text-xs">
                        🔒 安全
                      </Button>
                      <Button size="sm" variant="outline" className="flex-1 text-xs">
                        🔌 电力
                      </Button>
                    </div>
                    <div className="text-center text-gray-500 py-4">
                      <p className="text-xs">当前没有活跃的突发事件</p>
                      <Button size="sm" variant="ghost" className="text-xs mt-2">
                        创建随机事件
                      </Button>
                    </div>
                  </div>
                </CardContent>
              </Card>

              {/* POI管理 */}
              <Card>
                <CardHeader className="pb-2">
                  <CardTitle className="text-sm">POI管理</CardTitle>
                </CardHeader>
                <CardContent>
                  <div className="grid grid-cols-2 gap-2 text-xs mb-3">
                    <div className="text-center p-2 bg-blue-50 rounded">
                      <div className="font-medium">0</div>
                      <div className="text-gray-600">科室</div>
                    </div>
                    <div className="text-center p-2 bg-green-50 rounded">
                      <div className="font-medium">0</div>
                      <div className="text-gray-600">设备</div>
                    </div>
                  </div>
                  <div className="text-center text-gray-500 py-4">
                    <p className="text-xs">暂无POI数据</p>
                    <p className="text-xs mt-1">选择显示模式查看相关信息</p>
                  </div>
                </CardContent>
              </Card>

              {/* 操作控制 */}
              <Card>
                <CardHeader className="pb-2">
                  <CardTitle className="text-sm">操作控制</CardTitle>
                </CardHeader>
                <CardContent>
                  <div className="space-y-2">
                    <Button
                      size="sm"
                      className="w-full text-xs"
                      onClick={handleRefreshModel}
                    >
                      🔄 刷新数据
                    </Button>
                    <Button
                      size="sm"
                      variant="outline"
                      className="w-full text-xs"
                      onClick={() => {
                        if (selectedBuilding) {
                          mapViewerRef.current?.flyTo(selectedBuilding.center, 16)
                          toast.success('已重置视角')
                        }
                      }}
                    >
                      🎯 重置视角
                    </Button>
                    <Button
                      size="sm"
                      variant="outline"
                      className="w-full text-xs"
                      onClick={() => {
                        setShowDataPanel(!showDataPanel)
                        toast.success(showDataPanel ? '已隐藏数据面板' : '已显示数据面板')
                      }}
                    >
                      📊 切换面板
                    </Button>
                  </div>
                </CardContent>
              </Card>
            </div>
          </div>
        </div>
      </div>

      {/* AI助手浮窗 */}
      {showAIAssistant && selectedHospital && (
        <HospitalAIAssistant
          hospitalId={selectedHospital.id}
          onNavigateTo={handleAINavigation}
          onDepartmentSelect={handleAIDepartmentSelect}
          onBookAppointment={handleAIBookAppointment}
        />
      )}

      {/* 增强AI助手浮窗 - 可切换显示 */}
      {showDataPanel && (
        <div className="fixed top-4 right-4 w-80 bg-white rounded-lg shadow-lg border z-40">
          <div className="p-4 border-b">
            <div className="flex items-center justify-between">
              <h3 className="font-semibold flex items-center gap-2">
                <span className="text-2xl">🤖</span>
                AI助手增强版
              </h3>
              <Button 
                variant="ghost" 
                size="sm" 
                onClick={() => setShowDataPanel(false)}
              >
                ×
              </Button>
            </div>
          </div>
          <div className="p-4 space-y-3">
            <div className="text-sm text-gray-600 mb-2">当前医院: {selectedHospital?.name}</div>
            
            {/* AI功能快捷入口 */}
            <div className="grid grid-cols-2 gap-2">
              <Button 
                variant="outline" 
                size="sm" 
                className="text-xs h-12 flex flex-col gap-1"
                onClick={() => toast.success('正在启动智能对话...')}
              >
                💬
                <span>智能对话</span>
              </Button>
              
              <Button 
                variant="outline" 
                size="sm" 
                className="text-xs h-12 flex flex-col gap-1"
                onClick={() => toast.success('正在分析医院数据...')}
              >
                📊
                <span>数据分析</span>
              </Button>
              
              <Button 
                variant="outline" 
                size="sm" 
                className="text-xs h-12 flex flex-col gap-1"
                onClick={() => toast.success('正在进行预测分析...')}
              >
                🔮
                <span>预测分析</span>
              </Button>
              
              <Button 
                variant="outline" 
                size="sm" 
                className="text-xs h-12 flex flex-col gap-1"
                onClick={() => toast.success('正在启动语音助手...')}
              >
                🎤
                <span>语音助手</span>
              </Button>
            </div>

            {/* 实时AI建议 */}
            <div className="mt-4 p-3 bg-blue-50 rounded-lg border-l-4 border-blue-500">
              <p className="text-xs font-medium text-blue-900 mb-1">💡 AI建议</p>
              <p className="text-xs text-blue-700">
                建议为{selectedHospital?.name}配置更多POI点位，提升导航体验
              </p>
            </div>

            {/* AI分析结果 */}
            <div className="space-y-2">
              <div className="flex justify-between items-center text-xs">
                <span className="text-gray-600">科室覆盖率</span>
                <span className="font-medium">85%</span>
              </div>
              <div className="flex justify-between items-center text-xs">
                <span className="text-gray-600">设备监控率</span>
                <span className="font-medium">92%</span>
              </div>
              <div className="flex justify-between items-center text-xs">
                <span className="text-gray-600">AI准确率</span>
                <span className="font-medium text-green-600">96%</span>
              </div>
            </div>
          </div>
        </div>
      )}

      {/* 功能状态指示器 */}
      <div className="fixed bottom-4 left-4 flex flex-col gap-2">
        <div className="flex items-center gap-2 bg-white rounded-lg p-2 shadow-sm border text-xs">
          <div className="w-2 h-2 bg-green-500 rounded-full animate-pulse" />
          <span className="text-gray-600">系统运行正常</span>
        </div>

        {selectedHospital && (
          <div className="flex items-center gap-2 bg-white rounded-lg p-2 shadow-sm border text-xs">
            <div className="w-2 h-2 bg-blue-500 rounded-full" />
            <span className="text-gray-600">医院数据已加载</span>
          </div>
        )}

        {selectedBuilding && (
          <div className="flex items-center gap-2 bg-white rounded-lg p-2 shadow-sm border text-xs">
            <div className="w-2 h-2 bg-purple-500 rounded-full" />
            <span className="text-gray-600">建筑模型已加载</span>
          </div>
        )}
      </div>

      {/* 快速操作面板 */}
      {selectedHospital && selectedBuilding && (
        <div className="fixed top-1/2 right-4 transform -translate-y-1/2 space-y-2">
          <Card className="p-2">
            <div className="text-xs font-medium text-gray-700 mb-2 text-center">
              快速操作
            </div>
            <div className="space-y-1">
              <Button
                size="sm"
                variant="outline"
                className="w-full text-xs gap-1"
                onClick={() => handleRefreshModel()}
              >
                <Stethoscope className="w-3 h-3" />
                刷新数据
              </Button>
              <Button
                size="sm"
                variant="outline"
                className="w-full text-xs gap-1"
                onClick={() => mapViewerRef.current?.flyTo(selectedBuilding.center, 16)}
              >
                <Building2 className="w-3 h-3" />
                重置视角
              </Button>
            </div>
          </Card>
        </div>
      )}
    </div>
  )
}